<?php

/**
 * ECSHOP 
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liuhui $
 * $Id: index.php 15013 2010-03-25 09:31:42Z liuhui $
*/

define('IN_ECS', true);
define('ECS_ADMIN', true);



require(dirname(__FILE__) . '/includes/init.php');




require(ROOT_PATH . 'myplug/includes/lib_order.php');
require(ROOT_PATH . 'myplug/includes/lib_newfunction.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php'); 
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/common.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/admin/order.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');


$act=$_REQUEST['act'] ? $_REQUEST['act']:'default';


$dingyi = 1;



if ($act == 'default') {
	
	
	
	$dingyi = 2;
	 
	//DWH商品筛选分类以及搜索
	
	//分页
	$page = 1;
	$size = 16;
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE is_on_sale=1  and is_delete=0';
	//分类商品
	//$goods = $db->getAll($sql);
	
	$res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);		
	$goods = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		  $goods[$row['goods_id']]['goods_id']             = $row['goods_id'];	
		  $goods[$row['goods_id']]['goods_sn']             = $row['goods_sn'];	
		  $goods[$row['goods_id']]['goods_name']             = $row['goods_name'];	
		  $goods[$row['goods_id']]['shop_price']       = $row['shop_price'];
		  $goods[$row['goods_id']]['goods_thumb']       = $row['goods_thumb'];
		  $goods[$row['goods_id']]['goods_number']       = $row['goods_number'];
	}
	
		
	
	foreach($goods as $k=>$v){
		
		$properties = get_goods_properties($v['goods_id']);
		$goods[$k]['specification'] = $properties['spe'];
			
		$goods[$k]['num'] = count($properties['spe']);
	}
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE is_on_sale=1  and is_delete=0';
	//分类商品
	$record_count = $db->getAll($sql);
    $record_count  = count($record_count);
	$zongpage = ceil($record_count/16);
	$smarty->assign('zongpage',              $zongpage);	
	
	
	if( $_SESSION['user_id']>0){
	
		
	
	}else{
		
		$_SESSION['user_id'] =0;
		
	}
	
	$smarty->assign('yh',              $_SESSION['user_id']);
	
	$smarty->assign('user',              $_SESSION);	
	
	
	
	$sql = "select * from " .$ecs ->table('users')." where user_id=".$_SESSION['user_id'];
	$re = $db->getRow($sql);
	
	$_SESSION['user_name'] = $re['user_name'];
	
	$smarty->assign('sname',              substr($re['user_name'] , 0 , 1));	
	
	$smarty->assign('goods',              $goods);	
	
	$fenlei = get_categories_tree();
	
	$i=4;
	
	foreach($fenlei as $k=>$v){
		
		$fenlei[$k]['fid'] = $i;
		$i++;
		
	}
		

		
	
	$smarty->assign('categories',      $fenlei); // 分类树
	
	$sql = 'select * from'.$ecs->table('users').' where user_id='.$_SESSION['user_id'];
	//分类商品
	$customer = $db->getAll($sql);
	$smarty->assign('customer',              $customer);
	
	
	$sql = 'select * from'.$ecs->table('payment');
	//分类商品
	$payment = $db->getAll($sql);
	$smarty->assign('payment_list',              $payment);
	
	$sql = 'select * from'.$ecs->table('shipping')." limit 3";
	//分类商品
	$shipping = $db->getAll($sql);
	$smarty->assign('shipping_list',              $shipping);

	//用户数据显示  yjmp
	if ($_SESSION['user_id']) 
    {
        $user_info =  $GLOBALS['db']->getRow('SELECT user_name, email, display_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = '.$_SESSION['user_id']);
        $smarty->assign('user_name',$user_info['user_name']);
        $smarty->assign('display_name',$user_info['display_name']);
        $smarty->assign('email',$user_info['email']);
        $smarty->assign('on_hold_order', get_on_hold_info());

        
    }
    //获取钱箱当前数据 yjmp
    $crt_balance =  $GLOBALS['db']->getOne('SELECT balance FROM '.$GLOBALS['ecs']->table('cash_drawer').' WHERE 1 ORDER BY id DESC');
    $crt_balance = price_format($crt_balance,false);
    $cash_drawer = get_cash_drawer();

    $smarty->assign('crt_balance',$crt_balance);
    $smarty->assign('cash_drawer', $cash_drawer);
	
	//获取税类型
	$tax_type = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('tax_type').' WHERE 1');
	$smarty->assign('tax_type', $tax_type);
	
	$cartgoods = get_cart_goods();	
		
	
	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('zongji',              $cartgoods['total']);
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id'];
	$cnum = $db->getOne($sql);
	
	if($cnum){
		
	$result['cnum'] = $cnum;
	
	}else{
		
	$result['cnum'] = 0;	
	
	}
	
	if($cartgoods['total']['goods_amount']){
		
		$result['zongji'] = $cartgoods['total']['goods_amount'];
	}else{
		
		$result['zongji'] = '0.00';
	}
	
	$smarty->assign('result',              $result);
	
	
	include_once(ROOT_PATH .'includes/lib_transaction.php');
	$consignee_list[] = array('country' => $_CFG['shop_country']);
	/* 取得每个收货地址的省市区列表 */
	$province_list = array();
	$city_list = array();
	$district_list = array();
		
	
	foreach ($consignee_list as $region_id => $consignee)
	{
		$consignee['country']  = isset($consignee['country'])  ? intval($consignee['country'])  : 0;
		$consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0;
		$consignee['city']     = isset($consignee['city'])     ? intval($consignee['city'])     : 0;

		$province_list = get_regions(1,1);
		$city_list     = get_regions(2, $consignee['province']);
		$district_list = get_regions(3, $consignee['city']);
	}
	
	
	$smarty->assign('province_list', $province_list);
	$smarty->assign('city_list',     $city_list);
	$smarty->assign('district_list', $district_list);
	
	//miracle处理订单列表
	$pagecount = 20; //每页显示的数量。
	$smarty->assign('all_orderlist', get_user_orderlist($_SESSION['user_id'],1,$pagecount));
	$smarty->assign('dingyi', $dingyi);
	
    $smarty->display('index.html');
}
//miracle AJAX加载订单
elseif($act =='get_order_list'){
	$pages = empty($_REQUEST['pages']) ? 1 : $_REQUEST['pages'];
	$pagecount = 20; //每页显示的数量。
	$newpage = 0;
	$all_list = get_user_orderlist($_SESSION['user_id'],$pages,$pagecount);
	if(!empty($all_list)){
		$pages++;
		$newpage=1;
	}
		$smarty->assign('all_orderlist', $all_list);

		$result['opages'] = $pages;
		$result['newpage'] = $newpage;
		$result['content'] = $smarty->fetch('library/order_list.lbi');
	
	echo json_encode($result);
	die;
}
//miracle动态读取订单详细信息
elseif($act=='show_oinfo'){
	
	$oid = empty($_REQUEST['oid']) ? 0 : $_REQUEST['oid'];
	$smarty->assign('order', get_user_ordersinfo($oid));
	$smarty->assign('lang', $GLOBALS['_LANG']);
	$result['content'] = $smarty->fetch('library/order_info.lbi');
	echo json_encode($result);
	die;
}

//miracle再次购买
elseif($act=='addordergoods'){
	$order_id = empty($_REQUEST['oid']) ? 0 : $_REQUEST['oid'];
    $order_id = json_str_iconv($order_id);
    $ywid = $_SESSION['user_id'];
    $order = $db->getOne('SELECT count(*) FROM ' . $ecs->table('order_info') . ' WHERE order_id = ' . $order_id . ' and ywid = ' . $ywid);
    if (!$order) {
        $result = array('error' => 1, 'message' => $_LANG['repurchase_fail']);
        echo json_encode($result);
		die;
    }

    $db->query('DELETE FROM ' .$ecs->table('cart') . " WHERE rec_type = " . CART_REPURCHASE);
    $order_goods = $db->getAll("SELECT goods_id, goods_number, goods_attr_id, parent_id FROM " . $ecs->table('order_goods') . " WHERE order_id = " . $order_id);
    $result = array('error' => 0, 'message' => '');
    foreach ($order_goods as $goods) {
        $spec = empty($goods['goods_attr_id']) ? array() : explode(',', $goods['goods_attr_id']);
        if (!addto_cart($goods['goods_id'], $goods['goods_number'], $spec, $goods['parent_id'], CART_REPURCHASE)) {
            $result = false;
            $result = array('error' => 1, 'message' => $_LANG['repurchase_fail']);
        }
    }
	
	//更新购物车数量
	$cartgoods = get_cart_goods();	

	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('zongji',              		$cartgoods['total']);

	$result['zongji'] = $cartgoods['total']['goods_amount'];
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
	$cnum = $db->getOne($sql);
	
	$result['cnum'] = $cnum;
	
	$smarty->assign('result',              $result);
	
	$result['content'] = $smarty->fetch('library/total-right.lbi');
	
    echo json_encode($result);
	die;
}

//miracle退货详情
elseif($act=='refundorderinfo'){
	
	$order_id = $_POST['oid'] ? $_POST['oid'] : 0;
	$result = array('error'=>0,'message'=>'');
	if($order_id <= 0){
		$result = array('error'=>1,'message'=>'该订单不存在！');
		echo json_encode($result);
		die;
	}
	
	//获取订单商品
	$sql =" SELECT g.goods_name,g.goods_sn,g.goods_sn as sku,og.goods_price,og.goods_number,og.discount_fee FROM ".$GLOBALS['ecs']->table('goods')." as g LEFT JOIN ".$GLOBALS['ecs']->table('order_goods')." as og on g.goods_id=og.goods_id WHERE og.order_id = $order_id";
	$goods_list = $GLOBALS['db'] ->getAll($sql);
	//自定义商品处理
	$customer_goods = $GLOBALS['db']->getRow(' SELECT goods_name, goods_sn , goods_sn as sku, goods_price, goods_number, discount_fee FROM '.$GLOBALS['ecs']->table('order_goods').' WHERE order_id = "'.$order_id.'" AND goods_id = 0');
	if ($customer_goods) {
		array_push($goods_list, $customer_goods);
	}
	foreach($goods_list as $k=>$v){
		$goods_list[$k]['goods_price'] = price_format($v['goods_price'], false);
		$goods_list[$k]['discount_fee'] = price_format($v['discount_fee'], false);
		$goods_list[$k]['tax'] = price_format('0.00', false);//税收后期可能为变量
		$goods_list[$k]['total_price'] = price_format($v['goods_price']*$v['goods_number'], false);
	}
	
	$smarty->assign('goods_list',              $goods_list);
	$smarty->assign('order_id',                $order_id);
	
	$result['content'] = $smarty->fetch('library/refund_info.lbi');
	
    echo json_encode($result);
	die;
	

}

//miracle处理退货
elseif($act=='refundorderaction'){
	
	/* 定义当前时间 */
        define('GMTIME_UTC', gmtime()); // 获取 UTC 时间戳
		
		$result = array('error'=>0, 'message'=>'');
		
        /* 过滤数据 */
        $_REQUEST['refund'] = 3;
        $_REQUEST['refund_note'] = trim($_REQUEST['ordernode']) ? $_REQUEST['ordernode'] : '';//操作记录

		$ajust_refund = !empty($_REQUEST['ajust_refund']) ? $_REQUEST['ajust_refund'] : 0;//退款的差价
		$ajust_fee = trim($_REQUEST['ajust_fee']) ? $_REQUEST['ajust_fee'] : 0;//退款附加费

		$order_id = isset($_REQUEST['oid']) ? $_REQUEST['oid'] : 0;
		if($order_id<=0){
			$result = array('error'=>1, 'message'=>'该订单不存在');
			echo json_encode($result);
			die;
		}
		
		$order          = order_info($order_id);

		if($order['order_status'] == 4){
			$result = array('error'=>1, 'message'=>'该订单已经退款');
			echo json_encode($result);
			die;
		}
		
		
        /* 标记订单为“退货”、“未付款”、“未发货” */
        $arr = array('order_status' => OS_RETURNED,
            'pay_status' => PS_UNPAYED,
            'shipping_status' => SS_UNSHIPPED,
            'money_paid' => 0,
            'invoice_no' => '',
            'order_amount' => $order['money_paid']);
			update_order($order_id, $arr);
		
		//miracle更新订单额外信息
		$sql =" UPDATE ".$GLOBALS['ecs']->table('order_info')." SET ajust_refund = '$ajust_refund',ajust_fee='$ajust_fee' WHERE order_id = $order_id";
		$GLOBALS['db'] ->query($sql);
		
        /* todo 处理退款 */
        if ($order['pay_status'] != PS_UNPAYED) {
            $refund_type = $_REQUEST['refund'];
            $action_note = $refund_note = $_REQUEST['refund_note'];

            order_refund($order, $refund_type, $refund_note);
            error_log(var_export($order, 1), 3, __FILE__ . ".log");
            error_log("\r\n", 3, __FILE__ . ".log");
            error_log(var_export($refund_type, 1), 3, __FILE__ . ".log");
            error_log("\r\n", 3, __FILE__ . ".log");
            error_log(var_export($refund_note, 1), 3, __FILE__ . ".log");
        }


        /* 记录log */
        order_action($order['order_sn'], OS_RETURNED, SS_UNSHIPPED, PS_UNPAYED, $action_note, $_SESSION['user_name']);

        /* 如果订单用户不为空，计算积分，并退回 */
        if ($order['user_id'] > 0) {
            /* 取得用户信息 */
            $user = user_info($order['user_id']);

            $sql = "SELECT  goods_number, send_number FROM" . $GLOBALS['ecs']->table('order_goods') . "
                WHERE order_id = '" . $order['order_id'] . "'";

            $goods_num = $db->query($sql);
            $goods_num = $db->fetchRow($goods_num);

            if ($goods_num['goods_number'] == $goods_num['send_number']) {
                /* 计算并退回积分 */
                $integral = integral_to_give($order);
                log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf($_LANG['return_order_gift_integral'], $order['order_sn']));
            }
            /* todo 计算并退回红包 */
            return_order_bonus($order_id);

        }

        /* 如果使用库存，则增加库存（不论何时减库存都需要） */
        if ($_CFG['use_storage'] == '1') {
            if ($_CFG['stock_dec_time'] == SDT_SHIP) {
                change_order_goods_storage($order['order_id'], false, SDT_SHIP);
            } elseif ($_CFG['stock_dec_time'] == SDT_PLACE) {
                change_order_goods_storage($order['order_id'], false, SDT_PLACE);
            }
        }

        /* 退货用户余额、积分、红包 */
        return_user_surplus_integral_bonus($order);

        /* 获取当前操作员 */
        $delivery['action_user'] = $_SESSION['user_name'];
        /* 添加退货记录 */
        $delivery_list = array();
        $sql_delivery = "SELECT *
                         FROM " . $ecs->table('delivery_order') . "
                         WHERE status IN (0, 2)
                         AND order_id = " . $order['order_id'];
        $delivery_list = $GLOBALS['db']->getAll($sql_delivery);
        if ($delivery_list) {
            foreach ($delivery_list as $list) {
                $sql_back = "INSERT INTO " . $ecs->table('back_order') . " (delivery_sn, order_sn, order_id, add_time, shipping_id, user_id, action_user, consignee, address, Country, province, City, district, sign_building, Email,Zipcode, Tel, Mobile, best_time, postscript, how_oos, insure_fee, shipping_fee, update_time, suppliers_id, return_time, agency_id, invoice_no) VALUES ";

                $sql_back .= " ( '" . $list['delivery_sn'] . "', '" . $list['order_sn'] . "',
                              '" . $list['order_id'] . "', '" . $list['add_time'] . "',
                              '" . $list['shipping_id'] . "', '" . $list['user_id'] . "',
                              '" . $delivery['action_user'] . "', '" . $list['consignee'] . "',
                              '" . $list['address'] . "', '" . $list['country'] . "', '" . $list['province'] . "',
                              '" . $list['city'] . "', '" . $list['district'] . "', '" . $list['sign_building'] . "',
                              '" . $list['email'] . "', '" . $list['zipcode'] . "', '" . $list['tel'] . "',
                              '" . $list['mobile'] . "', '" . $list['best_time'] . "', '" . $list['postscript'] . "',
                              '" . $list['how_oos'] . "', '" . $list['insure_fee'] . "',
                              '" . $list['shipping_fee'] . "', '" . $list['update_time'] . "',
                              '" . $list['suppliers_id'] . "', '" . GMTIME_UTC . "',
                              '" . $list['agency_id'] . "', '" . $list['invoice_no'] . "'
                              )";
                $GLOBALS['db']->query($sql_back, 'SILENT');
                $back_id = $GLOBALS['db']->insert_id();

                $sql_back_goods = "INSERT INTO " . $ecs->table('back_goods') . " (back_id, goods_id, product_id, product_sn, goods_name,goods_sn, is_real, send_number, goods_attr)
                                   SELECT '$back_id', goods_id, product_id, product_sn, goods_name, goods_sn, is_real, send_number, goods_attr
                                   FROM " . $ecs->table('delivery_goods') . "
                                   WHERE delivery_id = " . $list['delivery_id'];
                $GLOBALS['db']->query($sql_back_goods, 'SILENT');
            }
        }

        /* 修改订单的发货单状态为退货 */
        $sql_delivery = "UPDATE " . $ecs->table('delivery_order') . "
                         SET status = 1
                         WHERE status IN (0, 2)
                         AND order_id = " . $order['order_id'];
        $GLOBALS['db']->query($sql_delivery, 'SILENT');

        /* 将订单的商品发货数量更新为 0 */
        $sql = "UPDATE " . $GLOBALS['ecs']->table('order_goods') . "
                SET send_number = 0
                WHERE order_id = '$order_id'";
        $GLOBALS['db']->query($sql, 'SILENT');
        // 更新订单crm
        //$is_succ = update_order_crm($order['order_sn']);
        /* if ($is_succ){
            sleep(3);
            // 退款请求crm
            $data['order_id'] = $order['order_sn'];
            $data['cur_money'] = $order['total_fee'];
            send_refund_to_crm($data);
        } */
        /* 清除缓存 */
        clear_cache_files();
		echo json_encode($result);
		die;
	
}
//miracle取消订单
elseif($act=='cancelorderaction'){
	/* 标记订单为“取消”，记录取消原因 */
	$order_id = isset($_REQUEST['oid']) ? $_REQUEST['oid'] : 0;
	$result = array('error'=>0, 'message'=>'');
	if($order_id<=0){
		$result = array('error'=>1, 'message'=>'该订单不存在');
		echo json_encode($result);
		die;
	}
	
	$order          = order_info($order_id);
	
	$action_note = $cancel_note = '业务操作取消订单';
	$arr = array(
		'order_status'  => OS_CANCELED,
		'to_buyer'      => $cancel_note,
		'pay_status'    => PS_UNPAYED,
		'pay_time'      => 0,
		'money_paid'    => 0,
		'order_amount'  => $order['money_paid']
	);
	update_order($order_id, $arr);

	/* 发送邮件 */
	$cfg = $_CFG['send_cancel_email'];
	if ($cfg == '1')
	{
		$tpl = get_mail_template('order_cancel');
		$smarty->assign('order', $order);
		$smarty->assign('shop_name', $_CFG['shop_name']);
		$smarty->assign('send_date', local_date($_CFG['date_format']));
		$smarty->assign('sent_date', local_date($_CFG['date_format']));
		$content = $smarty->fetch('str:' . $tpl['template_content']);
		if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']))
		{
			$result = array('error'=>1, 'message'=>$_LANG['send_mail_fail']);
			echo json_encode($result);
			die;
		}
	}
	
	/* todo 处理退款 */
	/* if ($order['money_paid'] > 0)
	{
		$refund_type = $_REQUEST['refund'];
		$refund_note = $_REQUEST['refund_note'];
		order_refund($order, $refund_type, $refund_note);
	} */

	/* 记录log */
	order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED, $action_note, $_SESSION['user_name']);

	/* 如果使用库存，且下订单时减库存，则增加库存 */
	if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE)
	{
		change_order_goods_storage($order_id, false, SDT_PLACE);
	}

	/* 退还用户余额、积分、红包 */
	return_user_surplus_integral_bonus($order);
	echo json_encode($result);
	die;

}

//miracle一键发货
elseif($act=='shipping_order'){
		//$invoice_no = '';

       /* if (!empty($invoice_no))

        { */
	$order_id = isset($_REQUEST['oid']) ? $_REQUEST['oid'] : 0;
	$result = array('error'=>0, 'message'=>'');
	if($order_id<=0){
		$result = array('error'=>1, 'message'=>'该订单不存在');
		echo json_encode($result);
		die;
	}
	$action_note = '业务员'.$_SESSION['user_name'].'操作发货';

    /* 查询：根据订单id查询订单信息 */
	$order = order_info($order_id);

	/* 查询：取得用户名 */
	if ($order['user_id'] > 0)
	{
		$user = user_info($order['user_id']);
		if (!empty($user))
		{
			$order['user_name'] = $user['user_name'];
		}
	}

    /* 查询：其他处理 */
	$order['order_time']    = local_date($_CFG['time_format'], $order['add_time']);

	$order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];

	/* 查询：是否保价 */
	$order['insure_yn'] = empty($order['insure_fee']) ? 0 : 1;
	/* 查询：是否存在实体商品 */
	$exist_real_goods = exist_real_goods($order_id);

	/* 查询：取得订单商品 */
	$_goods = get_order_goods(array('order_id' => $order['order_id'], 'order_sn' =>$order['order_sn']));

	$attr = $_goods['attr'];
	$goods_list = $_goods['goods_list'];
	unset($_goods);

	/* 查询：商品已发货数量 此单可发货数量 */
	if ($goods_list)
	{
		foreach ($goods_list as $key=>$goods_value)
		{
			if (!$goods_value['goods_id'])
			{
				continue;
			}

			/* 超级礼包 */

			if (($goods_value['extension_code'] == 'package_buy') && (count($goods_value['package_goods_list']) > 0))
			{
				$goods_list[$key]['package_goods_list'] = package_goods($goods_value['package_goods_list'], $goods_value['goods_number'], $goods_value['order_id'], $goods_value['extension_code'], $goods_value['goods_id']);
				
				foreach ($goods_list[$key]['package_goods_list'] as $pg_key => $pg_value)

				{
					$goods_list[$key]['package_goods_list'][$pg_key]['readonly'] = '';

					/* 使用库存 是否缺货 */

					if ($pg_value['storage'] <= 0 && $_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_SHIP)

					{

						$goods_list[$key]['package_goods_list'][$pg_key]['send'] = $_LANG['act_good_vacancy'];

						$goods_list[$key]['package_goods_list'][$pg_key]['readonly'] = 'readonly="readonly"';

					}

					/* 将已经全部发货的商品设置为只读 */

					elseif ($pg_value['send'] <= 0)

					{

						$goods_list[$key]['package_goods_list'][$pg_key]['send'] = $_LANG['act_good_delivery'];

						$goods_list[$key]['package_goods_list'][$pg_key]['readonly'] = 'readonly="readonly"';

					}

				}

			}

			else

			{

				$goods_list[$key]['sended'] = $goods_value['send_number'];

				$goods_list[$key]['sended'] = $goods_value['goods_number'];

				$goods_list[$key]['send'] = $goods_value['goods_number'] - $goods_value['send_number'];

				$goods_list[$key]['readonly'] = '';

				/* 是否缺货 */

				if ($goods_value['storage'] <= 0 && $_CFG['use_storage'] == '1'  && $_CFG['stock_dec_time'] == SDT_SHIP)

				{

					$goods_list[$key]['send'] = $_LANG['act_good_vacancy'];

					$goods_list[$key]['readonly'] = 'readonly="readonly"';

				}

				elseif ($goods_list[$key]['send'] <= 0)

				{

					$goods_list[$key]['send'] = $_LANG['act_good_delivery'];

					$goods_list[$key]['readonly'] = 'readonly="readonly"';

				}

			}

		}

	}

		$suppliers_id = 0;

		$delivery['order_sn'] = trim($order['order_sn']);

		$delivery['add_time'] = trim($order['order_time']);

		$delivery['user_id'] = intval(trim($order['user_id']));

		$delivery['how_oos'] = trim($order['how_oos']);

		$delivery['shipping_id'] = trim($order['shipping_id']);

		$delivery['shipping_fee'] = trim($order['shipping_fee']);

		$delivery['consignee'] = trim($order['consignee']);

		$delivery['address'] = trim($order['address']);

		$delivery['country'] = intval(trim($order['country']));

		$delivery['province'] = intval(trim($order['province']));

		$delivery['city'] = intval(trim($order['city']));

		$delivery['district'] = intval(trim($order['district']));

		$delivery['sign_building'] = trim($order['sign_building']);

		$delivery['email'] = trim($order['email']);

		$delivery['zipcode'] = trim($order['zipcode']);

		$delivery['tel'] = trim($order['tel']);

		$delivery['mobile'] = trim($order['mobile']);

		$delivery['best_time'] = trim($order['best_time']);

		$delivery['postscript'] = trim($order['postscript']);

		$delivery['how_oos'] = trim($order['how_oos']);

		$delivery['insure_fee'] = floatval(trim($order['insure_fee']));

		$delivery['shipping_fee'] = floatval(trim($order['shipping_fee']));

		$delivery['agency_id'] = intval(trim($order['agency_id']));

		$delivery['shipping_name'] = trim($order['shipping_name']);



    /* 查询订单信息 */

    $order = order_info($order_id);

    /* 检查能否操作 */

    $operable_list = operable_list($order);

	

    /* 初始化提示信息 */

   $msg = '';

		/* 定义当前时间 */

        /* 取得订单商品 */

        $_goods = get_order_goods(array('order_id' => $order_id, 'order_sn' => $delivery['order_sn']));

        $goods_list = $_goods['goods_list'];

		/* 检查此单发货商品库存缺货情况 */

        /* $goods_list已经过处理 超值礼包中商品库存已取得 */

        $virtual_goods = array();

        $package_virtual_goods = array();

        /* 生成发货单 */

        /* 获取发货单号和流水号 */

        $delivery['delivery_sn'] = get_delivery_sn();

        $delivery_sn = $delivery['delivery_sn'];



        /* 获取当前操作员 */

        $delivery['action_user'] = $_SESSION['admin_name'];



        /* 获取发货单生成时间 */

		define('GMTIME_UTC', gmtime()); 

        $delivery['update_time'] = GMTIME_UTC;

        $delivery_time = $delivery['update_time'];

        $sql ="select add_time from ". $GLOBALS['ecs']->table('order_info') ." WHERE order_sn = '" . $delivery['order_sn'] . "'";

        $delivery['add_time'] =  $GLOBALS['db']->GetOne($sql);

        /* 获取发货单所属供应商 */

        $delivery['suppliers_id'] = $suppliers_id;



        /* 设置默认值 */

        $delivery['status'] = 2; // 正常

        $delivery['order_id'] = $order_id;



        /* 过滤字段项 */

        $filter_fileds = array(

                               'order_sn', 'add_time', 'user_id', 'how_oos', 'shipping_id', 'shipping_fee',

                               'consignee', 'address', 'country', 'province', 'city', 'district', 'sign_building',

                               'email', 'zipcode', 'tel', 'mobile', 'best_time', 'postscript', 'insure_fee',

                               'agency_id', 'delivery_sn', 'action_user', 'update_time',

                               'suppliers_id', 'status', 'order_id', 'shipping_name'

                               );

        $_delivery = array();

        foreach ($filter_fileds as $value)

        {

            $_delivery[$value] = $delivery[$value];

        }

        /* 发货单入库 */

        $query = $db->autoExecute($ecs->table('delivery_order'), $_delivery, 'INSERT', '', 'SILENT');

        $delivery_id = $db->insert_id();

		$shipping_order_id = $db->getRow("select shipping_id from ".$ecs->table('delivery_order')."where delivery_id=".$delivery_id);

		$shipping_order_code = $db->getRow("select shipping_code from ".$ecs->table('shipping')."where shipping_id=".$shipping_order_id['shipping_id']);

		if ($shipping_order_code['shipping_code'] == "tc_express")

		{

			new_kuaidi_order($delivery_id);

			update_kuaidi_order($delivery_id, $invoice_no);

		}

		

		/* $sql_back_old = $db->getOne("SELECT back_id FROM " . $ecs->table('back_order') . " WHERE order_id = " . $order['order_id'] . " AND back_type = 4 AND status_back < 6 AND status_back != 3");

		if (!empty($sql_back_old))
		{
			$db->query("UPDATE " . $ecs->table('back_order') . " SET status_back = 6 WHERE back_id = " . $sql_back_old);

			$db->query("UPDATE " . $ecs->table('back_goods') . " SET status_back = 6 WHERE back_id = " . $sql_back_old);
		} */

        if ($delivery_id)
        {

            $delivery_goods = array();

			
            //发货单商品入库

            if (!empty($goods_list))

            {

                foreach ($goods_list as $value)

                {

                    if (empty($value['extension_code']) || $value['extension_code'] == 'virtual_card' || $value['extension_code'] == 'pre_sale')

                    /* 代码修改 By  www.68ecshop.com End */

                    {

                        $delivery_goods = array('delivery_id' => $delivery_id,

                                                'goods_id' => $value['goods_id'],

                                                'product_id' => $value['product_id'],

                                                'product_sn' => $value['product_sn'],

                                                'goods_id' => $value['goods_id'],

                                                'goods_name' => $value['goods_name'],

                                                'brand_name' => $value['brand_name'],

                                                'goods_sn' => $value['goods_sn'],

                                                'send_number' => $value['goods_number'],

                                                'parent_id' => 0,

                                                'is_real' => $value['is_real'],

                                                'goods_attr' => $value['goods_attr']

                                                );

                        /* 如果是货品 */

                        if (!empty($value['product_id']))

                        {

                            $delivery_goods['product_id'] = $value['product_id'];



                        }

                        $query = $db->autoExecute($ecs->table('delivery_goods'), $delivery_goods, 'INSERT', '', 'SILENT');

						$sql = "UPDATE ".$GLOBALS['ecs']->table('order_goods'). "

                SET send_number = " . $value['goods_number'] . "

                WHERE order_id = '" . $value['order_id'] . "'

                AND goods_id = '" . $value['goods_id'] . "' ";

                $GLOBALS['db']->query($sql, 'SILENT');

                    }

                    // 商品（超值礼包）

                    elseif ($value['extension_code'] == 'package_buy')

                    {

                        foreach ($value['package_goods_list'] as $pg_key => $pg_value)

                        {

                            $delivery_pg_goods = array('delivery_id' => $delivery_id,

                                                    'goods_id' => $pg_value['goods_id'],

                                                    'product_id' => $pg_value['product_id'],

                                                    'product_sn' => $pg_value['product_sn'],

                                                    'goods_name' => $pg_value['goods_name'],

                                                    'brand_name' => '',

                                                    'goods_sn' => $pg_value['goods_sn'],

                                                    'send_number' => $value['goods_number'],

                                                    'parent_id' => $value['goods_id'], // 礼包ID

                                                    'extension_code' => $value['extension_code'], // 礼包

                                                    'is_real' => $pg_value['is_real']

                                                    );

                            $query = $db->autoExecute($ecs->table('delivery_goods'), $delivery_pg_goods, 'INSERT', '', 'SILENT');

							$sql = "UPDATE ".$GLOBALS['ecs']->table('order_goods'). "

                SET send_number = " . $value['goods_number'] . "

                WHERE order_id = '" . $value['order_id'] . "'

                AND goods_id = '" . $value['goods_id'] . "' ";

                $GLOBALS['db']->query($sql, 'SILENT');

                        }

                    }

                }

            }

        }

        else

        {

            /* 操作失败 */

            $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
			$result = array('error'=>1,'message'=>$_LANG['act_false']);	
			echo json_encode($result);
			die;
        }

        unset($filter_fileds, $delivery, $_delivery, $order_finish);

        /* 定单信息更新处理 */

        if (true)

        {

            /* 标记订单为已确认 "发货中" */

            /* 更新发货时间 */

            $order_finish = get_order_finish($order_id);

            $shipping_status = SS_SHIPPED_ING;

            if ($order['order_status'] != OS_CONFIRMED && $order['order_status'] != OS_SPLITED && $order['order_status'] != OS_SPLITING_PART)

            {

                $arr['order_status']    = OS_CONFIRMED;

                $arr['confirm_time']    = time();

            }

            $arr['order_status'] = $order_finish ? OS_SPLITED : OS_SPLITING_PART; // 全部分单、部分分单

            $arr['shipping_status']     = $shipping_status;

            update_order($order_id, $arr);

		}



        /* 记录log */

        order_action($order['order_sn'], $arr['order_status'], $shipping_status, $order['pay_status'], $action_note, $_SESSION['user_name']);



        /* 清除缓存 */

        clear_cache_files();



	/* 根据发货单id查询发货单信息 */

    if (!empty($delivery_id))

    {

        $delivery_order = delivery_order_info($delivery_id);

    }

	elseif (!empty($order_sn))

    {



		$delivery_id = $GLOBALS['db']->getOne("SELECT delivery_id FROM " . $ecs->table('delivery_order') . " WHERE order_sn = " . $order_sn );

        $delivery_order = delivery_order_info($delivery_id);

    }

    else

    {

		$result = array('error'=>1,'message'=>'订单不存在');	
		echo json_encode($result);
		die;
    }


    /* 取得用户名 */

    if ($delivery_order['user_id'] > 0)

    {

        $user = user_info($delivery_order['user_id']);

        if (!empty($user))

        {

            $delivery_order['user_name'] = $user['user_name'];

        }

    }



    /* 取得区域名 */

    $sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .

                "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .

            "FROM " . $ecs->table('order_info') . " AS o " .

                "LEFT JOIN " . $ecs->table('region') . " AS c ON o.country = c.region_id " .

                "LEFT JOIN " . $ecs->table('region') . " AS p ON o.province = p.region_id " .

                "LEFT JOIN " . $ecs->table('region') . " AS t ON o.city = t.region_id " .

                "LEFT JOIN " . $ecs->table('region') . " AS d ON o.district = d.region_id " .

            "WHERE o.order_id = '" . $delivery_order['order_id'] . "'";

    $delivery_order['region'] = $db->getOne($sql);



    /* 是否保价 */

    $order['insure_yn'] = empty($order['insure_fee']) ? 0 : 1;



    /* 取得发货单商品 */

    $goods_sql = "SELECT *

                  FROM " . $ecs->table('delivery_goods') . "

                  WHERE delivery_id = " . $delivery_order['delivery_id'];

    $goods_list = $GLOBALS['db']->getAll($goods_sql);



    /* 是否存在实体商品 */

    $exist_real_goods = 0;

    if ($goods_list)

    {

        foreach ($goods_list as $value)

        {

            if ($value['is_real'])

            {

                $exist_real_goods++;

            }

        }

    }



    /* 取得订单操作记录 */

    $act_list = array();

    $sql = "SELECT * FROM " . $ecs->table('order_action') . " WHERE order_id = '" . $delivery_order['order_id'] . "' AND action_place = 1 ORDER BY log_time DESC,action_id DESC";

    $res = $db->query($sql);

    while ($row = $db->fetchRow($res))

    {

        $row['order_status']    = $_LANG['os'][$row['order_status']];

        $row['pay_status']      = $_LANG['ps'][$row['pay_status']];

        $row['shipping_status'] = ($row['shipping_status'] == SS_SHIPPED_ING) ? $_LANG['ss_admin'][SS_SHIPPED_ING] : $_LANG['ss'][$row['shipping_status']];

        $row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);

        $act_list[] = $row;

    }



	/*同步发货*/

	/*判断支付方式是否支付宝*/

	$alipay    = false;

	$order     = order_info($delivery_order['order_id']);  //根据订单ID查询订单信息，返回数组$order

	$payment   = payment_info($order['pay_id']);           //取得支付方式信息



    /* 定义当前时间 */

    define('GMTIME_UTC', gmtime()); // 获取 UTC 时间戳



    /* 根据发货单id查询发货单信息 */

    if (!empty($delivery_id))

    {

        $delivery_order = delivery_order_info($delivery_id);

    }

    else

    {

		$result = array('error'=>1,'message'=>'订单不存在');	
		echo json_encode($result);
		die;

    }



    /* 查询订单信息 */

    $order = order_info($order_id);



    /* 检查此单发货商品库存缺货情况 */

    $virtual_goods = array();

    $delivery_stock_sql = "SELECT DG.goods_id, DG.is_real, DG.product_id, SUM(DG.send_number) AS sums, IF(DG.product_id > 0, P.product_number, G.goods_number) AS storage, G.goods_name, DG.send_number

        FROM " . $GLOBALS['ecs']->table('delivery_goods') . " AS DG, " . $GLOBALS['ecs']->table('goods') . " AS G, " . $GLOBALS['ecs']->table('products') . " AS P

        WHERE DG.goods_id = G.goods_id

        AND DG.delivery_id = '$delivery_id'

        AND DG.product_id = P.product_id

        GROUP BY DG.product_id ";



    $delivery_stock_result = $GLOBALS['db']->getAll($delivery_stock_sql);



    /* 如果商品存在规格就查询规格，如果不存在规格按商品库存查询 */

    if(!empty($delivery_stock_result))

    {

        foreach ($delivery_stock_result as $value)

        {

            if (($value['sums'] > $value['storage'] || $value['storage'] <= 0) && (($_CFG['use_storage'] == '1'  && $_CFG['stock_dec_time'] == SDT_SHIP) || ($_CFG['use_storage'] == '0' && $value['is_real'] == 0)))

            {

                /* 操作失败 */

                $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
				
				$result = array('error'=>1,'message'=>sprintf($_LANG['act_good_vacancy'], $value['goods_name']));	
				echo json_encode($result);
				die;

                break;

            }



            /* 虚拟商品列表 virtual_card*/

            if ($value['is_real'] == 0)

            {

                $virtual_goods[] = array(

                               'goods_id' => $value['goods_id'],

                               'goods_name' => $value['goods_name'],

                               'num' => $value['send_number']

                               );

            }

        }

    }

    else

    {

        $delivery_stock_sql = "SELECT DG.goods_id, DG.is_real, SUM(DG.send_number) AS sums, G.goods_number, G.goods_name, DG.send_number

        FROM " . $GLOBALS['ecs']->table('delivery_goods') . " AS DG, " . $GLOBALS['ecs']->table('goods') . " AS G

        WHERE DG.goods_id = G.goods_id

        AND DG.delivery_id = '$delivery_id'

        GROUP BY DG.goods_id ";

        $delivery_stock_result = $GLOBALS['db']->getAll($delivery_stock_sql);

        foreach ($delivery_stock_result as $value)

        {

            if (($value['sums'] > $value['goods_number'] || $value['goods_number'] <= 0) && (($_CFG['use_storage'] == '1'  && $_CFG['stock_dec_time'] == SDT_SHIP) || ($_CFG['use_storage'] == '0' && $value['is_real'] == 0)))

            {

                /* 操作失败 */

                $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);

				$result = array('error'=>1,'message'=>sprintf($_LANG['act_good_vacancy'], $value['goods_name']));	
				echo json_encode($result);
				die;


                break;

            }



            /* 虚拟商品列表 virtual_card*/

            if ($value['is_real'] == 0)

            {

                $virtual_goods[] = array(

                               'goods_id' => $value['goods_id'],

                               'goods_name' => $value['goods_name'],

                               'num' => $value['send_number'],

                               );

            }

        }

    }



    /* 发货 */

    /* 处理虚拟卡 商品（虚货） */

    if (is_array($virtual_goods) && count($virtual_goods) > 0)

    {

        foreach ($virtual_goods as $virtual_value)

        {

            virtual_card_shipping($virtual_value,$order['order_sn'], $msg, 'split');

        }

    }



    /* 如果使用库存，且发货时减库存，则修改库存 */

    if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_SHIP)

    {



        foreach ($delivery_stock_result as $value)

        {



            /* 商品（实货）、超级礼包（实货） */

            if ($value['is_real'] != 0)

            {

                //（货品）

                if (!empty($value['product_id']))

                {

                    $minus_stock_sql = "UPDATE " . $GLOBALS['ecs']->table('products') . "

                                        SET product_number = product_number - " . $value['sums'] . "

                                        WHERE product_id = " . $value['product_id'];

                    $GLOBALS['db']->query($minus_stock_sql, 'SILENT');

                }



                $minus_stock_sql = "UPDATE " . $GLOBALS['ecs']->table('goods') . "

                                    SET goods_number = goods_number - " . $value['sums'] . "

                                    WHERE goods_id = " . $value['goods_id'];



                $GLOBALS['db']->query($minus_stock_sql, 'SILENT');

            }

        }

    }



    /* 修改发货单信息 */

    $invoice_no = trim($invoice_no);

    $_delivery['invoice_no'] = $invoice_no;

    $_delivery['status'] = 0; // 0，为已发货

    $query = $db->autoExecute($ecs->table('delivery_order'), $_delivery, 'UPDATE', "delivery_id = $delivery_id", 'SILENT');

    if (!$query)

    {

        /* 操作失败 */

        $links[] = array('text' => $_LANG['delivery_sn'] . $_LANG['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
		
		$result = array('error'=>1,'message'=>$_LANG['act_false']);	
		echo json_encode($result);
		die;
    }



    /* 标记订单为已确认 "已发货" */

    /* 更新发货时间 */

    $order_finish = get_all_delivery_finish($order_id);

    $shipping_status = ($order_finish == 1) ? SS_SHIPPED : SS_SHIPPED_PART;

    $arr['shipping_status']     = $shipping_status;

    $arr['shipping_time']       = time(); // 发货时间

    $arr['invoice_no']          = trim($order['invoice_no'] . '<br>' . $invoice_no, '<br>');

    update_order($order_id, $arr);



    /* 发货单发货记录log */

    order_action($order['order_sn'], OS_CONFIRMED, $shipping_status, $order['pay_status'], $action_note, $_SESSION['user_name'], 1);

    /* 如果当前订单已经全部发货 */

    if ($order_finish)

    {

        /* 如果订单用户不为空，计算积分，并发给用户；发红包 */

        if ($order['user_id'] > 0)

        {

            /* 取得用户信息 */

            $user = user_info($order['user_id']);



            /* 计算并发放积分 */

            $integral = integral_to_give($order);

            log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($_LANG['order_gift_integral'], $order['order_sn']));


            send_order_bonus($order_id,$order['supplier_id']);

        }



        /* 发送邮件 */

        $cfg = $_CFG['send_ship_email'];

        if ($cfg == '1')

        {

            $order['invoice_no'] = $invoice_no;

            $tpl = get_mail_template('deliver_notice');

            $smarty->assign('order', $order);

            $smarty->assign('send_time', local_date($_CFG['time_format']));

            $smarty->assign('shop_name', $_CFG['shop_name']);

            $smarty->assign('send_date', local_date($_CFG['date_format']));

            $smarty->assign('sent_date', local_date($_CFG['date_format']));

            $smarty->assign('confirm_url', $ecs->url() . 'receive.php?id=' . $order['order_id'] . '&con=' . rawurlencode($order['consignee']));

            $smarty->assign('send_msg_url',$ecs->url() . 'user.php?act=message_list&order_id=' . $order['order_id']);

            $content = $smarty->fetch('str:' . $tpl['template_content']);

            if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']))

            {
				$result = array('error'=>1,'message'=>$_LANG['send_mail_fail']);	
				echo json_encode($result);
				die;
            }

        }



        /* 如果需要，发短信 */

        if ($GLOBALS['_CFG']['sms_order_shipped'] == '1' && $order['mobile'] != '')

        {

            include_once('../send.php');

			$content = sprintf($_CFG['sms_order_shipped_tpl'],$order['order_sn'],$order['consignee'],$order['address'],$_CFG['sms_sign']);

			//$content = '您的订单已发货，订单号为'.$order['order_sn'].'收货人为'.$order['consignee'].'收货地址为'.$order['address'].'，请注意查收【'.$GLOBALS['_CFG']['shop_name'].'】';

				sendSMS($order['mobile'],$content);

        }

    }



    /* 清除缓存 */

    clear_cache_files();



    /* 操作成功 */

    $links[] = array('text' => $_LANG['09_delivery_order'], 'href' => 'order.php?act=delivery_list');

    $links[] = array('text' => $_LANG['delivery_sn'] . $_LANG['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);

	echo json_encode($result);
	die;

    /* } */
}

//miracle给用户发送邮件
elseif($act=='sendOrderemail'){
	$order_id = isset($_REQUEST['oid']) ? $_REQUEST['oid'] : 0;
	$email = trim($_REQUEST['email']) ? $_REQUEST['email'] : '';
	$result = array('error'=>0, 'message'=>'');
	if($order_id<=0){
		$result = array('error'=>1, 'message'=>'该订单不存在');
		echo json_encode($result);
		die;
	}
	$order = order_info($order_id);
	$order['order_status'] = $GLOBALS['_LANG']['os'][$order['order_status']] . ',' . $GLOBALS['_LANG']['ps'][$order['pay_status']] . ',' . $GLOBALS['_LANG']['ss'][$order['shipping_status']];
	//邮件内容
	$name = $order['consignee'];//邮件收件人
	$title = '订单提醒'; //邮件标题
	$content = "<p>{$name}您好！</p><p>您下的编号为{$order['order_sn']}的订单现在的状态为：{$order['order_status']}</p><p>感谢您在本店下单，祝您生活愉快。{$_CFG['shop_name']}</p>"; //邮件内容
	
	$res = send_mail($name,$email,$title,$content,'1');
	if(!$res){
		$result = array('error'=>1, 'message'=>'发送邮件失败');
		echo json_encode($result);
		die;
	}
	echo json_encode($result);
	die;
}

elseif($act=='change_comment'){
	$order_id = isset($_REQUEST['oid']) ? $_REQUEST['oid'] : 0;
	$content = trim($_REQUEST['content']) ? $_REQUEST['content'] : '';
	$result = array('error'=>0, 'message'=>'');
	if($order_id<=0){
		$result = array('error'=>1, 'message'=>'该订单不存在');
		echo json_encode($result);
		die;
	}
	//修改订单备注
	$sql =" UPDATE ".$GLOBALS['ecs']->table('order_info')." SET comment = '$content' WHERE order_id = $order_id";
	$GLOBALS['db'] ->query($sql);
	
	echo json_encode($result);
	die;
}

//miracle开发票
elseif($act=="send_invoice"){
	$order_id = isset($_REQUEST['oid']) ? $_REQUEST['oid'] : 0;
	$result = array('error'=>0, 'message'=>'');
	if($order_id<=0){
		$result = array('error'=>1, 'message'=>'该订单不存在');
		echo json_encode($result);
		die;
	}
	$sql =" SELECT invoice FROM ".$GLOBALS['ecs']->table('order_info')." WHERE order_id = $order_id";
	$invoice = $GLOBALS['db'] ->getOne($sql);
	if($invoice == 1){
		$result = array('error'=>1, 'message'=>'该订单已经开过发票');
		echo json_encode($result);
		die;
	}
	
	//修改订单发票状态
	$sql =" UPDATE ".$GLOBALS['ecs']->table('order_info')." SET invoice = 1 WHERE order_id = $order_id";
	$GLOBALS['db'] ->query($sql);
	
	echo json_encode($result);
	die;
}

elseif($act=='search_customer'){
  
 //搜索
	
	if($_POST['cname']){
		
		$wh1= " where user_name like '%".$_POST['cname']."%'";
		
		$sql = 'select * from'.$ecs->table('users').' '.$wh1.' ';
		//分类商品
		$customer = $db->getAll($sql);
	
	
		
	}
	
	
	
	
	$smarty->assign('customer',              $customer);
	
			
	
	$result['content'] = $smarty->fetch('library/search_customer.lbi');
		
	echo json_encode($result);
}


//hjl   添加顾客


elseif($act=='add_customer'){
  
  echo "<pre>";
  print_r($_POST);
  exit("!!!");
  
  die(json_encode('<p>hu jinle</p><span>hujinle@126.com</span>'));

}


//hjl  移除顾客 

elseif($act=='remove_customer'){
  
 

}

elseif($act=='addCustomerToCart'){
  
 
	$sql = "select * from " .$ecs ->table('users')." where user_id=".$_POST['uid'];
	$re = $db->getRow($sql);
	
	
	$smarty->assign('re',              $re);
	
	
	$sql = "select * from " .$ecs ->table('user_address')." where user_id=".$_POST['uid'];
	$re2 = $db->getRow($sql);
	
	
	
	$smarty->assign('re2',              $re2);
	
 
	$result['content'] = $smarty->fetch('library/addCustomerToCart.lbi');
	
	$result['content2'] = $smarty->fetch('library/gukeinfo.lbi');
	
	
		
	echo json_encode($result);
	
	
}


elseif($act=='saveShipping'){
  
	
	
	$user_id = $_SESSION['user_id'] ;
	$line1 =$_POST['shipping']['street'][0] ;
	$line2 =$_POST['shipping']['street'][1] ;
	$first_name =$_POST['shipping']['firstname'] ;
	$last_name =$_POST['shipping']['lastname'] ;
	$email =$_POST['shipping']['emailaddress'] ;
	$phone =$_POST['shipping']['telephone'] ;
	$city =$_POST['shipping']['city'] ;
	$zip =$_POST['shipping']['postcode'] ;
	$prvince =$_POST['shipping']['region_id'] ;
	$country =$_POST['shipping']['country_id'] ;
	$conpany =$_POST['shipping']['company'] ;
	$fax =$_POST['shipping']['fax'] ;
	
	$sql = "INSERT INTO " . $GLOBALS['ecs'] ->table('newadress') ." (user_id,first_name,last_name,email,phone,line1,line2,city,zip,country,province,conpany,fax) values ('$user_id','$first_name','$last_name','$email','$phone','$line1','$line2','$city','$zip','$country','$prvince','$conpany','$fax') ";
	$db->query($sql);
	
	
	
	
}

elseif($act=='saveyonghu'){
  						
	$user_id = $_SESSION['user_id'] ;
	$line1 =$_POST['billing']['street'][0] ;
	$line2 =$_POST['billing']['street'][1] ;
	$first_name =$_POST['billing']['firstname'] ;
	$last_name =$_POST['billing']['lastname'] ;
	$email =$_POST['billing']['email'] ;
	$phone =$_POST['billing']['telephone'] ;
	$city =$_POST['billing']['city'] ;
	$zip =$_POST['billing']['postcode'] ;
	$prvince =$_POST['billing']['region_id'] ;
	$country =$_POST['billing']['country_id'] ;
	$conpany =$_POST['billing']['company'] ;
	$fax =$_POST['billing']['fax'] ;
	$vatid =$_POST['billing']['vat_id'] ;
	
	$password = md5(123456);
	$time =time();
	
	$sql = "INSERT INTO " . $GLOBALS['ecs'] ->table('users') ." (email,user_name,password,mobile_phone,reg_time) values ('$email','$first_name','$password','$phone','$time') ";
	$db->query($sql);
	
	$user_id = $db->insert_id();
	
	$sql = "INSERT INTO " . $GLOBALS['ecs'] ->table('user_address') ." (user_id,consignee,email,mobile,address,zipcode,country,province,city,company,tel,vatid) values ('$user_id','$first_name','$email','$phone','$line1','$zip',1,'$country','$prvince','$conpany','$fax','$vatid') ";
	$db->query($sql); 
	
	
	
	$result = $user_id;
	
	echo json_encode($result);

}


elseif($act=='gxyonghu'){
	
	
	$line1 =$_POST['billing']['street'][0] ;
	$line2 =$_POST['billing']['street'][1] ;
	$first_name =$_POST['billing']['firstname'] ;
	$last_name =$_POST['billing']['lastname'] ;
	$email =$_POST['billing']['email'] ;
	$phone =$_POST['billing']['telephone'] ;
	$city =$_POST['billing']['city'] ;
	$zip =$_POST['billing']['postcode'] ;
	$prvince =$_POST['billing']['region_id'] ;
	$country =$_POST['billing']['country_id'] ;
	$conpany =$_POST['billing']['company'] ;
	$fax =$_POST['billing']['fax'] ;
	$vatid =$_POST['billing']['vat_id'] ;

	
	$sql = "UPDATE " . $GLOBALS['ecs']->table('user_address') . "
                SET consignee = '".$first_name."',
                    email = '".$email."',
                    country = 1,
                    province = '".$country."',
                    city = '".$prvince."',
                    address = '".$line1."',
                    zipcode = '".$zip."',
                    tel = '".$fax."',
                    mobile = '".$phone."',
                    company = '".$conpany."',
                    vatid = '".$vatid."' 
			WHERE user_id = ".$_GET['uid'];
				
    $GLOBALS['db']->query($sql); 
	
		
	/* $sql = "UPDATE " . $ecs->table('goods') . " SET goods_img = '$goods_img' WHERE user_id=".$_GET['uid'];
	
	$sql = "INSERT INTO " . $GLOBALS['ecs'] ->table('user_address') ." (user_id,consignee,email,mobile,address,zipcode,country,province,city,company,tel,vatid) values ('$user_id','$first_name','$email','$phone','$line1','$zip',1,'$country','$prvince','$conpany','$fax','$vatid') ";
	$db->query($sql); 
	
	*/	
	
	$result = $_GET['uid']; 
	
	echo json_encode($result);
	

}	

elseif ($act == 'fenye')
{
	//DWH商品筛选分类以及搜索
		
	
	//分页
	$page = $_POST['fynum'];
	$size = 16;
	
	
	if($_POST['cid'] > 0){
	
		$sql = 'select cat_id from'.$ecs->table('category').'WHERE parent_id='.$_POST['cid'];
		//分类商品
		$allcats = $db->getAll($sql);
		
		if(empty($allcats)){
			
			$wh1= " and cat_id=".$_POST['cid'];
			
		}else{
			
			foreach ($allcats as $v){  
			$v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串，join是别名  
			$temp[] = $v;  
			}  
			foreach($temp as $v){  
				$t.=$v.",";  
			}  
			$t=substr($t,0,-1);
							
			$wh1= " and cat_id in (".$t.")";
			
		}
	
	}else{
		
		$wh1 = "";
	}	
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE is_on_sale=1 '.$wh1.' and is_delete=0';
	//分类商品
	//$goods = $db->getAll($sql);
	
	$res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);		
	$goods = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		  $goods[$row['goods_id']]['goods_id']             = $row['goods_id'];	
		  $goods[$row['goods_id']]['goods_sn']             = $row['goods_sn'];	
		  $goods[$row['goods_id']]['goods_name']             = $row['goods_name'];	
		  $goods[$row['goods_id']]['shop_price']       = $row['shop_price'];
		  $goods[$row['goods_id']]['goods_thumb']       = $row['goods_thumb'];
		  $goods[$row['goods_id']]['goods_number']       = $row['goods_number'];
	}
	
	
	 
	foreach($goods as $k=>$v){
		
		$properties = get_goods_properties($v['goods_id']);
		$goods[$k]['specification'] = $properties['spe'];
			
		$goods[$k]['num'] = count($properties['spe']);
	}
	
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE is_on_sale=1 '.$wh1.' and is_delete=0';
	//分类商品
	$record_count = $db->getAll($sql);
	$record_count  = count($record_count);
	$zongpage = ceil($record_count/16);
	$smarty->assign('zongpage',              $zongpage);
	
	$smarty->assign('user',              $_SESSION);	
	
	$smarty->assign('goods',              $goods);	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id'];
	$cnum = $db->getOne($sql);
	
	if($cnum){
		
	$result['cnum'] = $cnum;
	
	}else{
		
	$result['cnum'] = 0;	
	
	}
	
	$result['fynum'] = $_POST['fynum'];
	$result['content'] = $smarty->fetch('library/search_list.lbi');
		
	echo json_encode($result);
	
}





elseif ($act == 'search')
{
	
	//搜索
	
	if($_POST['pname']){
		
		$wh1= " and goods_name like '%".$_POST['pname']."%'";
		
	}
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE is_on_sale=1 '.$wh1.' and is_delete=0';
	//分类商品
	$goods = $db->getAll($sql);
	
	$smarty->assign('goods',              $goods);
	
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id'];
	$cnum = $db->getOne($sql);
	
	if($cnum){
		
	$result['cnum'] = $cnum;
	
	}else{
		
	$result['cnum'] = 0;	
	
	}
	
	$result['content'] = $smarty->fetch('library/search_list.lbi');
		
	echo json_encode($result);
	
}

elseif ($act == 'catgoods')
{
	
	$sql = 'select cat_id from'.$ecs->table('category').'WHERE parent_id='.$_POST['cid'];
	//分类商品
	$allcats = $db->getAll($sql);
	
	if(empty($allcats)){
		
		$wh1= " and cat_id=".$_POST['cid'];
		
	}else{
		
		foreach ($allcats as $v){  
        $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串，join是别名  
        $temp[] = $v;  
		}  
		foreach($temp as $v){  
			$t.=$v.",";  
		}  
		$t=substr($t,0,-1);
						
		$wh1= " and cat_id in (".$t.")";
		
	}
	
	
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE is_on_sale=1 '.$wh1.' and is_delete=0';
	//分类商品
	$goods = $db->getAll($sql);
	
	foreach($goods as $k=>$v){
		
		$properties = get_goods_properties($v['goods_id']);
		$goods[$k]['specification'] = $properties['spe'];
			
		$goods[$k]['num'] = count($properties['spe']);
	}
	
	$smarty->assign('goods',              $goods);
	
	
	$record_count  = count($goods);
	$zongpage = ceil($record_count/16);
	$smarty->assign('zongpage',              $zongpage);
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id'];
	$cnum = $db->getOne($sql);
	
	if($cnum){
		
	$result['cnum'] = $cnum;
	
	}else{
		
	$result['cnum'] = 0;	
	
	}
	
	
	$result['cid'] = $_POST['cid'];

	$result['content'] = $smarty->fetch('library/search_list.lbi');
		
	echo json_encode($result);
	
}


	
	

elseif ($act == 'login')
{

	$user_name = !empty($_POST['username']) ? $_POST['username'] : '';
	$pwd = !empty($_POST['password']) ? $_POST['password'] : '';
	
	if ($user->check_user($user_name, $pwd) > 0)
		{
						
			
			
			$user->set_session($user_name);
			$user->set_cookie($user_name);
							
			
			
			$result['id'] = 1;
			$result['user_name'] = $user_name;
			if ($_SESSION['user_id']) 
		    {
		        $user_info =  $GLOBALS['db']->getRow('SELECT user_name, email, display_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = '.$_SESSION['user_id']);
		        $smarty->assign('user_name',$user_info['user_name']);
		        $smarty->assign('display_name',$user_info['display_name']);
		        $smarty->assign('email',$user_info['email']);
		    }
			$result['content'] = $smarty->fetch('library/edit_profile.lbi');

		}
		else
		{
			
				
			$result['id'] = 2;
		}
	
	echo json_encode($result);

}

elseif ($act == 'deleteProduct')
{
	$sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " where goods_id=".$_POST['goods_id']." and user_id=".$_SESSION['user_id'];
	$GLOBALS['db']->query($sql);
	
	
		$cartgoods = get_cart_goods();	
	
	
		
	$sql = "select goods_number from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']." and goods_id=".$_POST['goods_id'];
	$gnum = $db->getOne($sql);
	
	$result['gid'] = $_POST['gid'];
	
	if($gnum>1){
		
		$result['gnum'] = $gnum;
	}

	
	
	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('zongji',              $cartgoods['total']);
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
	$cnum = $db->getOne($sql);
	
	
	$result['cnum'] = $cnum;
	$result['zongji'] = $cartgoods['total']['goods_amount'];
	
	
	$smarty->assign('result',              $result);
			
	$result['content'] = $smarty->fetch('library/total-right.lbi');
			
	
	
	echo json_encode($result);
			
}

elseif ($act == 'showEditPopup')
{
	
	$cartgoods = get_cart_goods();	
		
	
	
	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('goods_id',              $_POST['gid']);
	
	
	
	$result['content'] = $smarty->fetch('library/showEditPopup.lbi');
	echo json_encode($result);
	
}

/* 退出会员中心 */
elseif ($act == 'logout')
{
	

	
	$user->logout();
	
		
	//$_SESSION['user_id']= "";
	//$_SESSION['user_name']= "";
		
	
	$Loaction = 'index.php';
	ecs_header("Location: $Loaction\n");
	exit; 
}

elseif ($act == 'addtocart')
{
		
	
	if(intval($_POST['guige']) > 0){
		
		$_POST['spec'][0] =  intval($_POST['guige']);
	
	}else{
		
		$_POST['spec'] = array();
	}
	
	$_POST['goods_id'] = $_POST['gid'];
	
	$_POST['number'] = 1;
	$_POST['parent'] = 0;
	
	
	
	
	addto_cart($_POST['gid'],$_POST['number'],$_POST['spec']);
		
	
	
	$cartgoods = get_cart_goods();	
	
	
		
	$sql = "select goods_number from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']." and goods_id=".$_POST['goods_id'];
	$gnum = $db->getOne($sql);
	
	$result['gid'] = $_POST['gid'];
	
	if($gnum>1){
		
		$result['gnum'] = $gnum;
	}

	
	
	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('zongji',              $cartgoods['total']);
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
	$cnum = $db->getOne($sql);
	
	
	$result['cnum'] = $cnum;
	$result['zongji'] = $cartgoods['total']['goods_amount'];
	
	
	$smarty->assign('result',              $result);
			
	$result['content'] = $smarty->fetch('library/total-right.lbi');
		
	echo json_encode($result);
	
}


elseif ($act == 'deltocart')
{
		
	$_POST['goods_id'] = $_POST['gid'];
	
	
	$sql = " UPDATE " .$ecs ->table('cart') . " SET goods_number=(goods_number-1) where user_id=".$_SESSION['user_id']." and goods_id=".$_POST['goods_id'];
	$db->query($sql);
		
	
	
		$cartgoods = get_cart_goods();	
	
	
		
	$sql = "select goods_number from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']." and goods_id=".$_POST['goods_id'];
	$gnum = $db->getOne($sql);
	
	$result['gid'] = $_POST['gid'];
	
	if($gnum>1){
		
		$result['gnum'] = $gnum;
	}

	
	
	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('zongji',              $cartgoods['total']);
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
	$cnum = $db->getOne($sql);
	
	
	$result['cnum'] = $cnum;
	$result['zongji'] = $cartgoods['total']['goods_amount'];
	
	
	$smarty->assign('result',              $result);
			
	$result['content'] = $smarty->fetch('library/total-right.lbi');
		

		
	echo json_encode($result);
	
}

elseif ($act == 'clearcart')
{
	$sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " where user_id=".$_SESSION['user_id'];
	$GLOBALS['db']->query($sql);
	
	
	$cartgoods = get_cart_goods();	
	
	
		
	$sql = "select goods_number from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id'];
	$gnum = $db->getOne($sql);
	
	$result['gid'] = $_POST['gid'];
	
	if($gnum>1){
		
		$result['gnum'] = $gnum;
	}

	
	
	$smarty->assign('cartgoods',              $cartgoods['goods_list']);
	
	$smarty->assign('zongji',              $cartgoods['total']);
	
	
	$sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
	$cnum = $db->getOne($sql);
	
	
	$result['cnum'] = $cnum;
	$result['zongji'] = $cartgoods['total']['goods_amount'];
	
	$smarty->assign('result',              $result);
	
	$result['content'] = $smarty->fetch('library/total-right.lbi');
	
	
	echo json_encode($result);
	
}


elseif ($act == 'gbprice')
{
	
	
	
}

	
elseif ($act == 'done')
{
	include_once('../includes/lib_clips.php');
    include_once('../includes/lib_payment.php');
	
	/* 取得购物类型 */
    $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS;
	
	//收货地址
	
	if($_POST['yhid']){
		
		$sql = "select * from " .$ecs ->table('user_address')." where user_id=".$_POST['yhid'];
		$consignee = $db->getRow($sql);
		
	}else{
		
		$sql = "select * from " .$ecs ->table('user_address')." where user_id=".$_SESSION['user_id'];
		$consignee = $db->getRow($sql);
	
	}
	
	$cart_goods = cart_goods($flow_type);
	
	$_POST['how_oos'] = isset($_POST['how_oos']) ? intval($_POST['how_oos']) : 0;
    $_POST['card_message'] = isset($_POST['card_message']) ? compile_str($_POST['card_message']) : '';
    $_POST['inv_type'] = !empty($_POST['inv_type']) ? compile_str($_POST['inv_type']) : '';
    $_POST['inv_payee'] = isset($_POST['inv_payee']) ? compile_str($_POST['inv_payee']) : '';
    $_POST['inv_content'] = isset($_POST['inv_content']) ? compile_str($_POST['inv_content']) : '';
    $_POST['postscript'] = isset($_POST['postscript']) ? compile_str($_POST['postscript']) : '';

    $order = array(
        'shipping_id'     => isset($_POST['shipping']) ? intval($_POST['shipping']) : 1,
        /* 'pay_id'          => intval($_POST['payment']), */
		'pay_id'    	  => isset($_POST['pay_id']) ? intval($_POST['pay_id']) : 1,
        'pack_id'         => isset($_POST['pack']) ? intval($_POST['pack']) : 0,
        'card_id'         => isset($_POST['card']) ? intval($_POST['card']) : 0,
        'card_message'    => trim($_POST['card_message']),
        'surplus'         => isset($_POST['surplus']) ? floatval($_POST['surplus']) : 0.00,
        'integral'        => isset($_POST['integral']) ? intval($_POST['integral']) : 0,
        'bonus_id'        => isset($_POST['bonus']) ? intval($_POST['bonus']) : 0,
        'need_inv'        => empty($_POST['need_inv']) ? 0 : 1,
        'inv_type'        => $_POST['inv_type'],
        'inv_payee'       => trim($_POST['inv_payee']),
        'inv_content'     => $_POST['inv_content'],
        'postscript'      => trim($_POST['postscript']),
        'how_oos'         => isset($_LANG['oos'][$_POST['how_oos']]) ? addslashes($_LANG['oos'][$_POST['how_oos']]) : '',
        'need_insure'     => isset($_POST['need_insure']) ? intval($_POST['need_insure']) : 0,
        'user_id'         => $_SESSION['user_id'],
        'add_time'        => gmtime(),
        'lastmodify'      => gmtime(),
        'order_status'    => OS_UNCONFIRMED,
        'shipping_status' => SS_UNSHIPPED,
        'pay_status'      => PS_UNPAYED,
        'agency_id'       => ""
        );
		
	$order['extension_code'] = '';
    $order['extension_id'] = 0;	
	$order['surplus']  = 0;
    $order['integral'] = 0;
	
	
	$order['ywid'] = $_SESSION['user_id'];
	
	if($_POST['comment']){
		$order['comment'] = $_POST['comment'];
		$_SESSION['comment'] = 	$order['comment'];
	}
	
	
	if($_POST['yhid']){
		
		$order['user_id'] = $_POST['yhid'];
	}else{
		
		$order['user_id'] = 0;
	}
	
	/* 检查红包是否存在 */
	
    /* if ($order['bonus_id'] > 0)
    {
        $bonus = bonus_info($order['bonus_id']);

        if (empty($bonus) || $bonus['user_id'] != $user_id || $bonus['order_id'] > 0 || $bonus['min_goods_amount'] > cart_amount(true, $flow_type))
        {
            $order['bonus_id'] = 0;
        }
    }*/
	
	
	
   /*  if (isset($_POST['bonus_sn']))
    {
        $bonus_sn = trim($_POST['bonus_sn']);
        $bonus = bonus_info(0, $bonus_sn);
        $now = gmtime();
        if (empty($bonus) || $bonus['user_id'] > 0 || $bonus['order_id'] > 0 || $bonus['min_goods_amount'] > cart_amount(true, $flow_type) || $now > $bonus['use_end_date'])
        {
        }
        else
        {
            if ($user_id > 0)
            {
                $sql = "UPDATE " . $ecs->table('user_bonus') . " SET user_id = '$user_id' WHERE bonus_id = '$bonus[bonus_id]' LIMIT 1";
                $db->query($sql);
            }
            $order['bonus_id'] = $bonus['bonus_id'];
            $order['bonus_sn'] = $bonus_sn;
        }
    }  */
	 
	 
	$order['bonus_id'] = 0;
	
	if($consignee){
		 /* 收货人信息 */
		foreach ($consignee as $key => $value)
		{
			$order[$key] = addslashes($value);
		} 
		
	}
	
	$total = order_fee($order, $cart_goods, $consignee);
	$order['bonus']        = $total['bonus'];
    $order['goods_amount'] = $total['goods_price'];
    $order['discount']     = $_POST['yhprice'];
    $order['surplus']      = $total['surplus'];
    $order['tax']          = $total['tax'];
    $order['order_amount']       = $order['goods_amount']-$order['discount'];
	 
	$result['order_amount'] = $order['order_amount'];
	 
	
	 
	 do
    {
		
        $order['order_sn'] = get_order_sn(); //获取新订单号
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT');
       
    }
    while ($error_no == 1062); //如果是订单号重复则重新提交数据

    $new_order_id = $db->insert_id();	
    $order['order_id'] = $new_order_id;

	$result['order_id'] = $order['order_id'];
	
	$sql = " UPDATE " .$ecs ->table('order_info') . " SET is_webpos=1 where order_id=".$order['order_id'];
	$db->query($sql);
	
    /* 插入订单商品 */
    $sql = "INSERT INTO " . $ecs->table('order_goods') . "( " .
                "order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id) ".
            " SELECT '$new_order_id', goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id".
            " FROM " .$ecs->table('cart') .
            " WHERE session_id = '".SESS_ID."' AND rec_type = '$flow_type'";
    $db->query($sql);
	
	clear_cart($flow_type);
		
	$result['order_sn'] = $order['order_sn'];
	
			
	echo json_encode($result);

}

	
//dwh加载分类

elseif ($act == 'allorder') {
    include_once('includes/cls_json.php');
    $json = new JSON;

	//分类ID
	$cid = $_GET['cid'];
	
	if($cid>0){
		
		$cwh = " cat_id =$cid and ";
		
	}else{
		
		$cwh = " ";
	}
	
	$sql = 'select * from'.$ecs->table('goods').'WHERE '.$cwh.' is_on_sale=1 and is_delete=0';
	//分类商品
	$goods = $db->getAll($sql);
	
	
	
	$smarty->assign('goods',              $goods);	
		
	
    $html = '';
    $html = $smarty->fetch('library/goods_list.lbi');
    $result = array(
        'error' => 0, 
        'html' => $html, 
        'total' => $total, 
        'page' => $page, 
        'id' => 'product_content', 
        'status' => 1
        );
      
    die($json->encode($result));
}

elseif ($act == 'ajaxdemo1') {
    include_once('includes/cls_json.php');
    $json = new JSON;

    $html = '';
    $html = $smarty->fetch('library/demo1.lbi');
    $result = array(
        'error' => 0, 
        'html' => $html, 
        'total' => $total, 
        'page' => $page, 
        'id' => 'demo1', 
        'status' => 1
        );

    die($json->encode($result));
}

elseif ($act == 'add_to_cart') {

    include_once('includes/cls_json.php');
	
    $_POST['goods']=strip_tags(urldecode($_POST['goods']));
	
    $_POST['goods'] = json_str_iconv($_POST['goods']);
	echo 'aaaa';exit;
	
	
	

    if (!empty($_REQUEST['goods_id']) && empty($_POST['goods']))
    {

        if (!is_numeric($_REQUEST['goods_id']) || intval($_REQUEST['goods_id']) <= 0)
        {
            ecs_header("Location:./\n");
        }
        $goods_id = intval($_REQUEST['goods_id']);
        exit;
    }

    $result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => '');
    $json  = new JSON;

    if (empty($_POST['goods']))
    {
        $result['error'] = 1;
        die($json->encode($result));
    }

    $goods = $json->decode($_POST['goods']);

    /* 检查：如果商品有规格，而post的数据没有规格，把商品的规格属性通过JSON传到前台 */
    if (empty($goods->spec) AND empty($goods->quick))
    {
        $sql = "SELECT a.attr_id, a.attr_name, a.attr_type, ".
            "g.goods_attr_id, g.attr_value, g.attr_price " .
        'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' .
        'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' .
        "WHERE a.attr_type != 0 AND g.goods_id = '" . $goods->goods_id . "' " .
        'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';

        $res = $GLOBALS['db']->getAll($sql);

        if (!empty($res))
        {
            $spe_arr = array();
            foreach ($res AS $row)
            {
                $spe_arr[$row['attr_id']]['attr_type'] = $row['attr_type'];
                $spe_arr[$row['attr_id']]['name']     = $row['attr_name'];
                $spe_arr[$row['attr_id']]['attr_id']     = $row['attr_id'];
                $spe_arr[$row['attr_id']]['values'][] = array(
                                                            'label'        => $row['attr_value'],
                                                            'price'        => $row['attr_price'],
                                                            'format_price' => price_format($row['attr_price'], false),
                                                            'id'           => $row['goods_attr_id']);
            }
            $i = 0;
            $spe_array = array();
            foreach ($spe_arr AS $row)
            {
                $spe_array[]=$row;
            }
            $result['error']   = ERR_NEED_SELECT_ATTR;
            $result['goods_id'] = $goods->goods_id;
            $result['parent'] = $goods->parent;
            $result['message'] = $spe_array;

            die($json->encode($result));
        }
    }

    /* 更新：如果是一步购物，先清空购物车 */
    if ($_CFG['one_step_buy'] == '1')
    {
        clear_cart();
    }

    /* 检查：商品数量是否合法 */
    if (!is_numeric($goods->number) || intval($goods->number) <= 0)
    {
        $result['error']   = 1;
        $result['message'] = $_LANG['invalid_number'];
    }
    /* 更新：购物车 */
    else
    {
        if(!empty($goods->spec))
        {
            foreach ($goods->spec as  $key=>$val )
            {
                $goods->spec[$key]=intval($val);
            }
        }
        // 更新：添加到购物车
        if (addto_cart($goods->goods_id, $goods->number, $goods->spec, $goods->parent))
        {
            if ($_CFG['cart_confirm'] > 2)
            {
                $result['message'] = '';
            }
            else
            {
                $result['message'] = $_CFG['cart_confirm'] == 1 ? $_LANG['addto_cart_success_1'] : $_LANG['addto_cart_success_2'];
            }

            $result['content'] = insert_cart_info();
            $result['one_step_buy'] = $_CFG['one_step_buy'];
        }
        else
        {
            $result['message']  = $err->last_message();
            $result['error']    = $err->error_no;
            $result['goods_id'] = stripslashes($goods->goods_id);
            if (is_array($goods->spec))
            {
                $result['product_spec'] = implode(',', $goods->spec);
            }
            else
            {
                $result['product_spec'] = $goods->spec;
            }
        }
    }

    $result['confirm_type'] = !empty($_CFG['cart_confirm']) ? $_CFG['cart_confirm'] : 2;
	
	
	
	
	
	
    die($json->encode($result));
	
	
}


elseif($act=='getGoodsList'){
    include_once('includes/cls_json.php');
    $json = new JSON;
	
	$catid=intval($_POST['catid']);

	$children = get_children($catid);
	
	$best_goods_list = get_category_recommend_goods('best',$children);
	
	print_r($best_goods_list);exit;
	
	
    $smarty->assign('best_goods_list',$best_goods_list);   //分类下的商品列表

    $html = '';
    $html = $smarty->fetch('library/goods_list.lbi');
	//id 是前台的ID
    $result = array(
        'error' => 0, 
        'html' => $html, 
        'total' => $total, 
        'page' => $page, 
        'id' => 'product_content',    
        'status' => 1
        );
      
    die($json->encode($result));
	
}



?>
